package com.imooc.town.service;

import com.mysql.jdbc.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.simpleframework.xml.core.Commit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * create by song on 2018/3/29
 * To change this template use File | Settings | File Templates.
 * desc:
 * 加锁，
 */

@Component
@Slf4j
public class RedisLock {



    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean lock(String key,String value){
        if (redisTemplate.opsForValue().setIfAbsent (key,value)){
            return true;
        }

        String currentValue = redisTemplate.opsForValue ().get(key);
//        如果锁过期
        if (!StringUtils.isNullOrEmpty ( currentValue )&&Long.parseLong ( currentValue )<System.currentTimeMillis ()){
//            获取上一个锁的时间
            String oldValue = redisTemplate.opsForValue ().getAndSet ( key,value );
            if (!StringUtils.isNullOrEmpty ( oldValue )&& oldValue.equals ( currentValue )){
                return  true;
            }
        }
        return false;
    }

    public void unLock(String key,String value){
        try {
            String currentValue = redisTemplate.opsForValue ().get ( key );
            if (!StringUtils.isNullOrEmpty ( currentValue )&&currentValue.equals ( value )){
                redisTemplate.opsForValue ().getOperations ().delete ( key );
            }
        } catch (Exception e) {
            log.error ( "【redis分布式异常】解锁异常，{}",e );
        }

    }


}
